package com.more.offer.exercise.jdkproxy02;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * @author pinoc
 * @date 2021/7/24
 * @description
 */
public class JdkProxyLearn {

	public static void main(String[] args) {
		System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
		Caculator proxy = JdkProxyLearn.getProxy(new CaculatorImpl());
		int add = proxy.add(1, 1);
		System.out.println("result= " + add);
		System.out.println(proxy.getClass());
	}

	private static Caculator getProxy(Caculator caculator){
		ClassLoader classLoader = caculator.getClass().getClassLoader();
		Class<?>[] interfaces = caculator.getClass().getInterfaces();
		InvocationHandler invocationHandler = (proxy, method, args) -> {
			Object result = null;
			if("add".equals(method.getName())) {
				System.out.println("执行add方法");
			}
			result = method.invoke(caculator, args);
			return result;

		};
		//进行proxy的实例化 传入invocation实例
		Object proxy = Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
		return (Caculator) proxy;
	}
}
